<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-title">美味外卖</div>
      <div class="register-subtitle">{{ roleTexts[activeRole] }}注册</div>
      
      <el-tabs v-model="activeRole" @tab-click="handleRoleChange">
        <el-tab-pane label="用户" name="user"></el-tab-pane>
        <el-tab-pane label="商家" name="merchant"></el-tab-pane>
        <el-tab-pane label="骑手" name="rider"></el-tab-pane>
      </el-tabs>
      
      <el-form :model="registerForm" :rules="registerRules" ref="registerForm" class="register-form">
        <!-- 公共字段 -->
        <el-form-item prop="username">
          <el-input v-model="registerForm.username" prefix-icon="el-icon-user" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerForm.password" prefix-icon="el-icon-lock" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" prefix-icon="el-icon-lock" type="password" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="registerForm.phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        
        <!-- 商家特有字段 -->
        <template v-if="activeRole === 'merchant'">
          <div class="application-notice">
            <el-alert
              title="商家入驻需要提供以下资料，审核通过后方可登录"
              type="info"
              :closable="false">
            </el-alert>
          </div>
          <el-form-item prop="storeName">
            <el-input v-model="registerForm.storeName" prefix-icon="el-icon-office-building" placeholder="请输入店铺名称"></el-input>
          </el-form-item>
          <el-form-item prop="contact">
            <el-input v-model="registerForm.contact" prefix-icon="el-icon-user" placeholder="请输入联系人姓名"></el-input>
          </el-form-item>
          <el-form-item prop="address">
            <el-input v-model="registerForm.address" prefix-icon="el-icon-location" placeholder="请输入店铺地址"></el-input>
          </el-form-item>
          <el-form-item prop="description">
            <el-input v-model="registerForm.description" type="textarea" :rows="3" placeholder="请输入店铺简介"></el-input>
          </el-form-item>
          <el-form-item prop="businessType">
            <el-select v-model="registerForm.businessType" placeholder="请选择经营类型" style="width: 100%;">
              <el-option label="快餐便当" value="快餐便当"></el-option>
              <el-option label="特色菜系" value="特色菜系"></el-option>
              <el-option label="甜品饮品" value="甜品饮品"></el-option>
              <el-option label="小吃夜宵" value="小吃夜宵"></el-option>
              <el-option label="水果生鲜" value="水果生鲜"></el-option>
              <el-option label="超市便利" value="超市便利"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="licenseImage" label="营业执照">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleLicenseSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传营业执照扫描件，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="idCardFront" label="身份证正面">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleIdCardFrontSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传身份证正面照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="idCardBack" label="身份证背面">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleIdCardBackSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传身份证背面照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="bankCard">
            <el-input v-model="registerForm.bankCard" prefix-icon="el-icon-bank-card" placeholder="请输入银行卡号"></el-input>
          </el-form-item>
          <el-form-item prop="bankName">
            <el-input v-model="registerForm.bankName" prefix-icon="el-icon-office-building" placeholder="请输入开户行"></el-input>
          </el-form-item>
        </template>
        
        <!-- 骑手特有字段 -->
        <template v-if="activeRole === 'rider'">
          <div class="application-notice">
            <el-alert
              title="骑手入驻需要提供以下资料，审核通过后方可登录"
              type="info"
              :closable="false">
            </el-alert>
          </div>
          <el-form-item prop="name">
            <el-input v-model="registerForm.name" prefix-icon="el-icon-user" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          <el-form-item prop="idNumber">
            <el-input v-model="registerForm.idNumber" prefix-icon="el-icon-document" placeholder="请输入身份证号"></el-input>
          </el-form-item>
          <el-form-item prop="vehicleType" label="车辆类型">
            <el-select v-model="registerForm.vehicleType" placeholder="请选择车辆类型" style="width: 100%;">
              <el-option label="自行车" value="bicycle"></el-option>
              <el-option label="电动车" value="scooter"></el-option>
              <el-option label="摩托车" value="motorcycle"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="idCardFront" label="身份证正面">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleRiderIdFrontSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传身份证正面照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="idCardBack" label="身份证背面">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleRiderIdBackSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传身份证背面照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="driverLicense" label="驾驶证" v-if="registerForm.vehicleType !== 'bicycle'">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleDriverLicenseSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传驾驶证照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="vehicleLicense" label="行驶证" v-if="registerForm.vehicleType !== 'bicycle'">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleVehicleLicenseSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传行驶证照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="riderPhoto" label="骑手照片">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleRiderPhotoSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">请上传骑手本人照片，只能上传jpg/png文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item prop="bankCard">
            <el-input v-model="registerForm.bankCard" prefix-icon="el-icon-bank-card" placeholder="请输入银行卡号"></el-input>
          </el-form-item>
          <el-form-item prop="bankName">
            <el-input v-model="registerForm.bankName" prefix-icon="el-icon-office-building" placeholder="请输入开户行"></el-input>
          </el-form-item>
        </template>
        
        <el-form-item>
          <el-button type="primary" class="register-button" @click="handleRegister" :loading="loading">注册</el-button>
        </el-form-item>
        <div class="register-options">
          <span class="login-link" @click="$router.push('/login')">已有账号，去登录</span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { submitMerchantApplication, submitRiderApplication, uploadFile } from '@/api/application';

export default {
  name: 'Register',
  data() {
    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      activeRole: 'user',
      roleTexts: {
        user: '用户',
        merchant: '商家',
        rider: '骑手'
      },
      roleUrls: {
        user: '/register',
        merchant: '/merchant/apply',
        rider: '/rider/apply'
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        phone: '',
        // 商家特有字段
        storeName: '',
        contact: '',
        address: '',
        description: '',
        businessType: '',
        licenseImage: '',
        idCardFront: '',
        idCardBack: '',
        bankCard: '',
        bankName: '',
        // 骑手特有字段
        name: '',
        idNumber: '',
        vehicleType: 'scooter',
        driverLicense: '',
        vehicleLicense: '',
        riderPhoto: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入店铺简介', trigger: 'blur' }
        ],
        businessType: [
          { required: true, message: '请选择经营类型', trigger: 'change' }
        ],
        licenseImage: [
          { required: true, message: '请上传营业执照扫描件', trigger: 'change' }
        ],
        idCardFront: [
          { required: true, message: '请上传身份证正面照片', trigger: 'change' }
        ],
        idCardBack: [
          { required: true, message: '请上传身份证背面照片', trigger: 'change' }
        ],
        bankCard: [
          { required: true, message: '请输入银行卡号', trigger: 'blur' }
        ],
        bankName: [
          { required: true, message: '请输入开户行', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        vehicleType: [
          { required: true, message: '请选择车辆类型', trigger: 'change' }
        ],
        driverLicense: [
          { required: true, message: '请上传驾驶证照片', trigger: 'change' }
        ],
        vehicleLicense: [
          { required: true, message: '请上传行驶证照片', trigger: 'change' }
        ],
        riderPhoto: [
          { required: true, message: '请上传骑手本人照片', trigger: 'change' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleRoleChange() {
      this.$refs.registerForm.resetFields()
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 移除确认密码字段
          const formData = {...this.registerForm}
          delete formData.confirmPassword
          
          // 用户注册直接走注册接口
          if (this.activeRole === 'user') {
            this.$http.post(this.roleUrls[this.activeRole], formData)
              .then(res => {
                if (res.data.code === 200) {
                  this.$message.success('注册成功，请登录')
                  this.$router.push('/login')
                } else {
                  this.$message.error(res.data.message || '注册失败')
                }
              })
              .catch(err => {
                console.error(err)
                this.$message.error('注册失败，请稍后再试')
              })
              .finally(() => {
                this.loading = false
              })
          } else if (this.activeRole === 'merchant') {
            // 商家申请入驻
            submitMerchantApplication(formData)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success('商家入驻申请提交成功，请等待审核')
                  this.$router.push('/login')
                } else {
                  this.$message.error(res.message || '申请提交失败')
                }
              })
              .catch(err => {
                console.error(err)
                this.$message.error('申请提交失败，请稍后再试')
              })
              .finally(() => {
                this.loading = false
              })
          } else if (this.activeRole === 'rider') {
            // 骑手申请入驻
            submitRiderApplication(formData)
              .then(res => {
                if (res.code === 200) {
                  this.$message.success('骑手入驻申请提交成功，请等待审核')
                  this.$router.push('/login')
                } else {
                  this.$message.error(res.message || '申请提交失败')
                }
              })
              .catch(err => {
                console.error(err)
                this.$message.error('申请提交失败，请稍后再试')
              })
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },
    // 文件上传相关方法
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    handleUploadError(err) {
      console.error('上传失败:', err)
      this.$message.error('文件上传失败，请重试')
    },
    // 通用上传方法
    uploadFileToServer(file) {
      this.loading = true
      return uploadFile(file)
        .then(response => {
          this.loading = false
          return response
        })
        .catch(err => {
          this.loading = false
          throw err
        })
    },
    // 商家文件上传处理
    handleLicenseSuccess(response) {
      if (response.code === 200) {
        this.registerForm.licenseImage = response.data
        this.$message.success('营业执照上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleIdCardFrontSuccess(response) {
      if (response.code === 200) {
        this.registerForm.idCardFront = response.data
        this.$message.success('身份证正面上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleIdCardBackSuccess(response) {
      if (response.code === 200) {
        this.registerForm.idCardBack = response.data
        this.$message.success('身份证背面上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    // 骑手文件上传处理
    handleRiderIdFrontSuccess(response) {
      if (response.code === 200) {
        this.registerForm.idCardFront = response.data
        this.$message.success('身份证正面上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleRiderIdBackSuccess(response) {
      if (response.code === 200) {
        this.registerForm.idCardBack = response.data
        this.$message.success('身份证背面上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleDriverLicenseSuccess(response) {
      if (response.code === 200) {
        this.registerForm.driverLicense = response.data
        this.$message.success('驾驶证上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleVehicleLicenseSuccess(response) {
      if (response.code === 200) {
        this.registerForm.vehicleLicense = response.data
        this.$message.success('行驶证上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    handleRiderPhotoSuccess(response) {
      if (response.code === 200) {
        this.registerForm.riderPhoto = response.data
        this.$message.success('骑手照片上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  padding: 20px 0;
}
.register-box {
  width: 400px;
  padding: 40px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.register-title {
  font-size: 28px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
  margin-bottom: 10px;
}
.register-subtitle {
  font-size: 18px;
  text-align: center;
  color: #666;
  margin-bottom: 20px;
}
.register-form {
  margin-top: 30px;
}
.register-button {
  width: 100%;
}
.register-options {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  color: #409EFF;
  font-size: 14px;
}
.login-link {
  cursor: pointer;
}
.application-notice {
  margin-bottom: 20px;
}
</style> 